const socketWrapper = require('./index');
const { redisGet, delKey } = require('../utils/redis')
const redisUtils = require('../utils/redisUtils')

// 等待 Socket.IO 初始化完成后再使用
function setUserOnline() {
    try {
        const io = socketWrapper.getIO();
        io.on('connection', async (socket) => {
            //console.log('新客户端连接:', socket.id, socket.uid);
            socket.on('userOnline', async (data, callback) => {
                if (!data) {
                    callback({
                        code: 500,
                        message: 'data is required'
                    })
                    return
                }
                // console.log('userOnline', data)
                const uids = Array.isArray(data) ? data : [data]
                const uidsInfo = []
                for (let i = 0; i < uids.length; i++) {
                    const uid = uids[i]
                    const userInfo = await redisGet(`mim-${uid}`)
                    if (userInfo) {
                        uidsInfo.push({
                            user: uid,
                            online: userInfo.online || 0
                        })
                    } else {
                        continue
                    }
                }
                callback({
                    code: 200,
                    message: "OK",
                    data: uidsInfo
                })
            });
        });
    } catch (error) {
        console.error('Socket.IO 未初始化:', error);
    }
}

module.exports = setUserOnline;